import MediaDeviceDao from '../dao/MediaDeviceDao';
class MediaStreamController {
	/**
	 * 创建流
	 * @returns
	 */
	public createMediaStream() {
		return new Promise((resolve, reject) => {
			ivcs.agent.createStreamWithMediaTrackConstraints(
				{ audioConstraints: MediaDeviceDao.audioStreamConstraints, videoConstraints: MediaDeviceDao.videoStreamConstraints, publishOptions: MediaDeviceDao.publishOptions },
				(stream: { mediaStream: MediaStream }) => {
					MediaDeviceDao.setLocalStream(stream.mediaStream);
					resolve(MediaDeviceDao.localStream);
				},
				(error: any) => {
					console.log('createStreamWithMediaTrackConstraints error:', error);
					reject(error);
				}
			);
		});
	}

	/**
	 * 替换流
	 * @param {string} videoId
	 * @returns
	 */
	public replaceVideoStream(videoId: string) {
		return new Promise((resolve, reject) => {
			try {
				let video = document.getElementById(videoId) as HTMLVideoElement;
				if (video) {
					video.srcObject = MediaDeviceDao.localStream;
					video.play();
					resolve('ok');
				}
			} catch (error) {
				console.log('replaceVideoStream error:', error);
				reject(error);
			}
		});
	}

	public updateStreamWithDeviceID(videoId: string, deviceId: string) {
		return new Promise((resolve, reject) => {
			if (!MediaDeviceDao.validateDeviceID(deviceId)) {
				console.error(`${deviceId} is invalid`);
				reject('');
			}
			try {
				const device = MediaDeviceDao.findDeviceWithDevicID(deviceId);
				if (device?.kind === 'audioinput') {
					MediaDeviceDao.setAudioStreamConstraints({ ...MediaDeviceDao.audioStreamConstraints, deviceId: device.deviceId });
				}
				if (device?.kind === 'videoinput') {
					MediaDeviceDao.setVideoStreamConstraints({ ...MediaDeviceDao.videoStreamConstraints, deviceId: device.deviceId });
				}

				this.createMediaStream()
					.then(async stream => {
						await this.replaceVideoStream(videoId);
						resolve(stream);
					})
					.catch(e => reject(e));
			} catch (error) {
				reject(error);
			}
		});
	}
}

export default MediaStreamController;
